package cn.ivicar.oss.quartz;

import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.TotalStatistic;
import cn.com.carsmart.ws.model.Vehicle;
import cn.com.carsmart.ws.service.TotalStatisticManager;
import cn.com.carsmart.ws.service.VehicleManager;
import cn.ivicar.oss.guice.OssGuiceConfig;
import cn.ivicar.redis.JedisClusterFactory;
import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisCluster;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 定时统计激活设备总数，在线总数，离线总数
 */
public class TotalStatisticJob implements Job {

    private static transient final Logger LOGGER = LoggerFactory.getLogger(TotalStatisticJob.class);

    private static final String IOV_INTERACTION = "iov:interaction";
    private static final String IOV_STAUTUS = "iov:status";
    private static final String IOV_ONLINE = "iov:online:";

    private static TotalStatisticManager totalStatisticManager = OssGuiceConfig.getStaticInjector().getInstance(TotalStatisticManager.class);
    private static VehicleManager vehicleManager = OssGuiceConfig.getStaticInjector().getInstance(VehicleManager.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        LOGGER.info(String.format("定时任务：TotalStatisticJob开始执行，开始时间 = %s",sdf.format(new Date())));
        //已激活设备总数
        int activateStat = 0;
        JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
        Set<String> clientIds = cluster.hgetAll(IOV_INTERACTION).keySet();
        activateStat =  clientIds.size();

        int offLineCount = 0;
        int onLineStat = 0;
        if(clientIds != null && clientIds.size()>0){
            BaseExample example = vehicleManager.getExample();

            for(String clientId:clientIds){
                String status = cluster.hget(IOV_STAUTUS, clientId);
                if(StringUtils.isNotBlank(status)){
                    if("0".equalsIgnoreCase(status)){
                        offLineCount++;
                    }
                }
                String isOnline = cluster.get(IOV_ONLINE+clientId);
                if(StringUtils.isNotBlank(isOnline)){
                    if("1".equalsIgnoreCase(isOnline)){
                        onLineStat++;
                    }
                }

                example.or().andPropertyEqualTo(clientId,"serial");
                int i = this.vehicleManager.countByExample(example);
                if(i == 0){
                    Vehicle vehicle = new Vehicle();
                    vehicle.setSerial(clientId);
                    vehicle.setCreated(new Date());
                    vehicle.setUpdated(new Date());
                    this.vehicleManager.insert(vehicle);
                }
                example.clear();

            }
        }

        TotalStatistic totalStatistic = new TotalStatistic();
        totalStatistic.setInteractionCount(activateStat);
        totalStatistic.setOnlineCount(onLineStat);
        totalStatistic.setOfflineCount(offLineCount);
        totalStatistic.setCreated(new Date());
        totalStatistic.setUpdated(new Date());

        this.totalStatisticManager.insert(totalStatistic);
        LOGGER.info(String.format("定时任务:TotalStatisticJob执行完毕！结束时间：%s=",sdf.format(new Date())));
    }
}
